package com.itxckf.controller;

import com.itxckf.pojo.Address;
import com.itxckf.pojo.LoginUser;
import com.itxckf.pojo.Result;
import com.itxckf.pojo.User;
import com.itxckf.service.LoginService;
import com.itxckf.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
/**
 * 登录操作
 */
public class LoginController {
    @Autowired
    private LoginService loginService;
    @PostMapping("/login")
//    跨域操作
    public Result userLogin(@RequestBody User user){
        log.info("用户登录,{}",user.getUsername(), user.getPassword());
//        检验数据库是否有这个用户
        User e = loginService.login(user);
//        登录成功,生成令牌,下发令牌
        if(e != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",e.getUserID());
            claims.put("name",e.getUsername());
            claims.put("username",e.getUsername());
            String jwt = JwtUtils.generateJwt(claims);  //jwt 账号信息
            List<User> getUser = loginService.getUser(e.getUserID());
            LoginUser loginUser = new LoginUser(getUser,jwt);
            return Result.success(loginUser);
        }
        return Result.error("用户或密码错误！");
    };
    @PostMapping("/register")
    public Result userRegister(@RequestBody User user){
        log.info("用户注册,{}",user);
//        检验数据库是否有这个用户
        User e = loginService.isUser(user.getUsername());
        log.info("账号信息,{}",e);
        if(e != null){
            return Result.error("账号已存在！");
        }else{
            user.setTotalConsumption(0);
            user.setBalance("0");
            loginService.register(user);
            return Result.success("注册成功");
        }
    };

    @GetMapping("/home")
    public Result getHome(){
        log.info("获取首页数据");
        return Result.success();
    };
}